const apiPath = '/api/modules/'
const siteApiPath = apiPath + 'site/'

// modules
async function getModules() {
	try {
		const response = await $.ajax({
			url: apiPath + 'get',
			type: 'GET',
		})
	
		const { code, msg, data } = response

		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const { domain, adminKey } = data

		const http = location.protocol === 'https:' ? 'https' : 'http'
		const url = `${http}//${domain}/admin/login.html?adminKey=${adminKey}`

		$('#textAddress').attr('href', url).text(url)
		
		for (let key in data) {
			if (data.hasOwnProperty(key)) {
				const $input = $(`input[name="${key}"]`)
					, $select = $(`select[name="${key}"]`)
					, val = data[key]

				if ($input.length > 0) {
					$input.val(val)
				}

				else if ($select.length > 0) {
					$select.selectpicker()

					const $option = $select.find('option')

					$select.selectpicker('val', val)

					$option.each(function (_index, item) {
						if ($(item).val() === val) {
							$(item).attr('selected', 'selected')
						}
					})
				}
				
				else {
					console.warn('暂无匹配')
					continue
				}
			} else {
				console.warn('暂无匹配')
			}
		}
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

async function getSite() {
	const $siteTable = $('#siteTable')
	$siteTable.text('加载中...')

	try {
		const response = await $.ajax({
			url: siteApiPath + 'get',
			type: 'GET',
		})
			
		const { code, msg, data } = response
		
		if (code !== 200) {
			$siteTable.text(msg)
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		let tr = ''

		data.forEach(item => {
			tr += `
				<tr class="text-center align-middle">
					<td>${item.id}</td>
					<td style="min-width: 150px;">${item.name}</td>
					<td><a href="${item.link}" target="_blank" rel="noopener noreferrer">${item.link}</a></td>
					<td>
						${item.img ? `<img class="lazyload" data-src="${item.img}" style="border: 1px solid #ccc; border-radius: 5px; max-height: 120px; min-width: 150px">` : '<p style="max-height: 100px; line-height: 100px;">默认</p>'}
					</td>
					<td>
						<div class="btn-group btn-group-sm">
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="编辑"
								onclick="set(${item.id}, '${item.name}', '${item.link}', '${item.img || ''}')"
							><i class="mdi mdi-pencil"></i></a>
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="移除"
								onclick="del(${item.id})"
							><i class="mdi mdi-window-close"></i></a>
						</div>
					</td>
				</tr>
			`
		})
		$siteTable.html(tr)

		$('.lazyload').lazyload({
			root: null,
			rootMargin: '100px',
			threshold: 0
		})
		// 渲染工具
		renderTooltip()
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

async function add() {
	$.confirm({
		title: '新增站点',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点名称</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-name" placeholder="请输入站点名称" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点链接</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" placeholder="请输入站点链接" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点图片【不填默认获取文字】</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" placeholder="请输入站点图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const name = that.find('#input-name').val()
					const link = that.find('#input-link').val()
					const img = that.find('#input-img').val()

					const data = {
						name,
						link,
						img: img || ''
					}
					if (!$.trim(name) || !$.trim(link)) {
						$.alert({
							title: '',
							content: '网站名称和链接不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: siteApiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '添加成功',
								type: 'green'
							})

							getSite()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

async function set(id, name, link, img) {
	$.confirm({
		title: '更新站点',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点名称</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-name" value="${name}" placeholder="请输入站点名称" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点链接</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" value="${link}" placeholder="请输入站点链接" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">站点图片【不填默认获取文字】</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" value="${img || ''}" placeholder="请输入站点图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const name = that.find('#input-name').val()
					const link = that.find('#input-link').val()
					const img = that.find('#input-img').val()

					const data = {
						id,
						name,
						link,
						img: img || ''
					}
					if (!$.trim(name) || !$.trim(link)) {
						$.alert({
							title: '',
							content: '网站名称和链接不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: siteApiPath + 'set',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '更新成功',
								type: 'green'
							})

							getSite()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

function del(id) {
	$.confirm({
		title: `确定删除id为: ${id}的站点吗`,
		content: '确定删除吗?',
		type: 'red',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-danger',
				action: function () {
					$.ajax({
						url: siteApiPath + `del?id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							getSite()
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}

$(document).ready(function (e) {
	$('input, textarea').attr('autocomplete', 'off')

	getModules()

	getSite()

	$('#siteForm').on('submit', async function (e) {
		e.preventDefault()
	
		const formArrayInfo = $(this).serializeArray()
		let batchData = []
	
		$.each(formArrayInfo, function (_index, item) {
			batchData.push({
				module: item.name,
				xf_values: item.value || ''
			})
		})
	
		const size = batchData.length - 1
	
		batchData.forEach(async (item, i) => {
			const jsonStr = JSON.stringify(item)
			
			try {
				const response = await $.ajax({
					url: apiPath + 'set',
					type: 'POST',
					data: jsonStr,
					contentType: 'application/json'
				})
		
				const { code, msg } = response
				
				if (code !== 200) {
					showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
					return
				}
				if (i === size) {
					showNotify(msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'right')
					return
				}
			} catch (error) {
				showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
				console.error('服务器有误: ', error)
			}
		})
	})
})